package form;

import connection.ConnectionManager;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextField;

/**
 *
 * @author hz
 */
public class ConnectDialog extends javax.swing.JDialog {

    public ConnectDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        mainFrame = (MainFrame) parent;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        addressLabel = new javax.swing.JLabel();
        nameLabel = new javax.swing.JLabel();
        connectButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        nameField = new javax.swing.JTextField();
        addressField1 = new javax.swing.JTextField();
        addressField2 = new javax.swing.JTextField();
        addressField3 = new javax.swing.JTextField();
        addressField4 = new javax.swing.JTextField();
        semiColon = new javax.swing.JLabel();
        portField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(312, 120));
        setResizable(false);
        getContentPane().setLayout(null);

        addressLabel.setFont(new java.awt.Font("Ubuntu", 1, 15));
        addressLabel.setText("Nickname:");
        addressLabel.setName("addressLabel"); // NOI18N
        getContentPane().add(addressLabel);
        addressLabel.setBounds(5, 35, 81, 19);

        nameLabel.setFont(new java.awt.Font("Ubuntu", 1, 15));
        nameLabel.setText("IP Address:");
        nameLabel.setName("nameLabel"); // NOI18N
        nameLabel.setRequestFocusEnabled(false);
        nameLabel.setVerifyInputWhenFocusTarget(false);
        getContentPane().add(nameLabel);
        nameLabel.setBounds(2, 5, 86, 19);

        connectButton.setMnemonic('c');
        connectButton.setText("Connect");
        connectButton.setToolTipText("Connect to IP");
        connectButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        connectButton.setName("connectButton"); // NOI18N
        connectButton.setPreferredSize(new java.awt.Dimension(97, 30));
        connectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectButtonActionPerformed(evt);
            }
        });
        getContentPane().add(connectButton);
        connectButton.setBounds(120, 60, 97, 30);

        cancelButton.setText("Cancel");
        cancelButton.setToolTipText("Cancel connect");
        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.setPreferredSize(new java.awt.Dimension(89, 30));
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        getContentPane().add(cancelButton);
        cancelButton.setBounds(219, 60, 89, 30);

        nameField.setName("nameField"); // NOI18N
        nameField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                nameFieldKeyTyped(evt);
            }
        });
        getContentPane().add(nameField);
        nameField.setBounds(82, 30, 227, 28);

        addressField1.setName("addressField1"); // NOI18N
        addressField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                addressFieldKeyTyped(evt);
            }
        });
        getContentPane().add(addressField1);
        addressField1.setBounds(83, 0, 41, 28);

        addressField2.setName("addressField2"); // NOI18N
        addressField2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                addressFieldKeyTyped(evt);
            }
        });
        getContentPane().add(addressField2);
        addressField2.setBounds(126, 0, 41, 28);

        addressField3.setName("addressField3"); // NOI18N
        addressField3.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                addressFieldKeyTyped(evt);
            }
        });
        getContentPane().add(addressField3);
        addressField3.setBounds(169, 0, 41, 28);

        addressField4.setName("portField"); // NOI18N
        addressField4.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                addressFieldKeyTyped(evt);
            }
        });
        getContentPane().add(addressField4);
        addressField4.setBounds(212, 0, 41, 28);

        semiColon.setText(":");
        semiColon.setName("semiColon"); // NOI18N
        semiColon.setPreferredSize(new java.awt.Dimension(6, 18));
        getContentPane().add(semiColon);
        semiColon.setBounds(255, 5, 6, 18);

        portField.setText("5678");
        portField.setName("addressField4"); // NOI18N
        portField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                portFieldKeyTyped(evt);
            }
        });
        getContentPane().add(portField);
        portField.setBounds(262, 0, 46, 28);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
        //Parse ip and connect
        if (addressField1 != null
                && addressField2 != null
                && addressField3 != null
                && addressField4 != null
                && portField != null) {
            try {
                StringBuilder string = new StringBuilder();
                string.append(addressField1.getText()).append('.');
                string.append(addressField2.getText()).append('.');
                string.append(addressField3.getText()).append('.');
                string.append(addressField4.getText());
                connMan = mainFrame.getConnMan();
                connMan.setAddress(string.toString());
                connMan.setPort(Integer.parseInt(portField.getText().toString()));

                //We should be able to open a socket without looping a thread? Since there is a listening server.
                connMan.connect();
                
                //connMan.start();
                //connMan.join();
                if (connMan.isConnected()) {
                	dispose();
                } else {
                	mainFrame.hostFail();
                	dispose();
                }
            } catch (UnknownHostException ex){
                Logger.getLogger(ConnectDialog.class.getName()).log(Level.SEVERE, "I don't think the host is listening..", ex);
            } catch (IOException ex) {
                //Logger.getLogger(ConnectDialog.class.getName()).log(Level.SEVERE, "Something broke while trying to connect..", ex);
            	mainFrame.hostFail();
            	dispose();
    	
            }
        }

    }//GEN-LAST:event_connectButtonActionPerformed

    private void addressFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_addressFieldKeyTyped
        // Only valid values are numbers.
        // Can't enter more than 3 characters
        if (evt.getSource().equals(addressField1)
                || evt.getSource().equals(addressField2)
                || evt.getSource().equals(addressField3)
                || evt.getSource().equals(addressField4)) {
            if (((JTextField) evt.getSource()).getText().length() > 2) {
                evt.setKeyChar('\n');
            }
            if (evt.getKeyChar() < '0' || evt.getKeyChar() > '9') {
                evt.setKeyChar('\n');
            }
        }
    }//GEN-LAST:event_addressFieldKeyTyped

    private void portFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_portFieldKeyTyped
        // If sum of evt and field both are > 65536, then invalid

        if (portField.getText().length() > 4) {
            evt.setKeyChar('\n');
        }
    }//GEN-LAST:event_portFieldKeyTyped

    private void nameFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nameFieldKeyTyped
        if (((JTextField) evt.getSource()).getText().length() > 24) {
            evt.setKeyChar('\n');
        }
        else {
            MainFrame.currentPlayer.setNickName(nameField.getText() + evt.getKeyChar());
            //System.out.println(nameField.getText());

        }
    }//GEN-LAST:event_nameFieldKeyTyped

    public String getNickName() {
        return nameField.getText();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ConnectDialog dialog = new ConnectDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField addressField1;
    private javax.swing.JTextField addressField2;
    private javax.swing.JTextField addressField3;
    private javax.swing.JTextField addressField4;
    private javax.swing.JLabel addressLabel;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton connectButton;
    private javax.swing.JTextField nameField;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField portField;
    private javax.swing.JLabel semiColon;
    // End of variables declaration//GEN-END:variables
    private MainFrame mainFrame;
    private ConnectionManager connMan;
}
